package com.utils.loadManager
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	
	/**
	 * 独立加载器 
	 * @author Mr.Lu
	 */
	
	public class LoaderObject
	{
		private var _url:String = '';//地址
		private var _loaderName:String = '';//文件名
		
		private var _loader:Loader;//加载器
		private var _loadContent:*;//加载对象
		private var _freeState:Boolean = true;//空闲状态

		private var _loaderCallBack:Function;//加载完毕，回调函数
		
		public function LoaderObject()
		{
		}
		
		
		/**
		 * 二进制数据加载
		 * @param bytes 二进制数据
		 */		
		public function loadBytes(bytes:ByteArray):void
		{
			if(!bytes) return;
			createNewLoader();
			_loader.loadBytes(bytes);
		}
		
		/**
		 * 链接加载 
		 * @param url 文件路径
		 */		
		public function loadUrl(url:String):void
		{
			_url = url;
			if(!_url) return;
			loaderName = _url;
			createNewLoader();
			_loader.load(new URLRequest(_url));
		}
		
		/**创建加载器*/		
		private function createNewLoader():void
		{
			if(_loader) return;
			_freeState = false;//标记为忙碌状态
			_loader = new Loader();
			_loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onIOErrorEventHandler);
			_loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onCompleteHandler);
		}
		
		/**加载完成后，抛出完成事件*/		
		private function onCompleteHandler(e:Event):void
		{
			_loadContent = _loader.content;
			
			if(_loaderCallBack is Function) _loaderCallBack(_loader.content);
			
			_freeState = true;//清理重置空闲状态
			
			clearLoader();
		}
		
		private function onIOErrorEventHandler(e:IOErrorEvent):void
		{
			trace('【'+loaderName + '】-->Error:'+e.text);
		}
		
		/**设置加载文件名*/
		public function set loaderName(value:String):void
		{
			if(_loaderName != '') return;
			var list:Array = value.split('/');
			_loaderName = list[list.length-1];
		}
		
		/**加载的文件*/		
		public function get loadContent():*{return _loadContent;}
		
		/**加载的文件名*/		
		public function get loaderName():String{return _loaderName;}
		
		/**清理loader*/		
		public function clearLoader():void
		{
			if(!_loader) return;
			_loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,onIOErrorEventHandler);
			_loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,onCompleteHandler);
			_loader.unload();
			_loader = null;
		}
		
		/**数据销毁*/		
		public function dispose():void
		{
			if(_loader) clearLoader();
			_loadContent = null;
			_freeState = true;
			_url = '';
			_loaderName = '';
			_loaderCallBack = null;
		}
		
		/**加载完毕回调函数*/		
		public function set loaderCallBack(value:Function):void{_loaderCallBack = value;}
		
		/**空闲状态标记*/		
		public function get freeState():Boolean{return _freeState;}
		
	}
}